package com.colortea.action.frontstage.goods;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.colortea.action.backstage.base.BaseTAction;
import com.colortea.action.backstage.base.DataCollectionTAction;
import com.colortea.action.backstage.utils.BaseTools;
import com.colortea.action.backstage.utils.enums.BaseEnums.DataShowState;
import com.colortea.action.backstage.utils.enums.BaseEnums.DataUsingState;
import com.colortea.action.backstage.utils.statickey.FreeMarkervariable;
import com.colortea.action.backstage.utils.statickey.StaticKey;
import com.colortea.action.frontstage.utils.Arith;
import com.colortea.action.frontstage.utils.PageModel;
import com.colortea.action.frontstage.vo.RedisGoodsCommentVo;
import com.colortea.entity.GoodsCommentT;
import com.colortea.entity.GoodsDetailRpT;
import com.colortea.entity.GoodsT;
import com.colortea.entity.MemberT;
import com.colortea.redis.service.RedisBaseTService;
import com.colortea.service.GoodsCommentTService;
import com.colortea.service.GoodsTService;
import com.colortea.service.impl.Serial;
import com.opensymphony.xwork2.ActionContext;

@ParentPackage("colortea")
@Namespace("/goods")
@InterceptorRefs({ @InterceptorRef("defaultStack") })
public class GoodsDetailAction extends BaseTAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Resource
	private GoodsTService goodsTService;
	@Resource
	private GoodsCommentTService goodsCommentTService;
	@Resource
	private DataCollectionTAction dataCollectionTAction;
	@Resource
	private RedisBaseTService<RedisGoodsCommentVo> redisBaseTService;

	/**
	 * 获取商品详情页
	 * 1，获取商品详情
	 * 2，计算评论数据（从redis读取评论数据）
	 * 3，评论数据放入redis
	 * @return
	 */
	@Action(value = "getGoodsDetail", results = {
			@Result(name = "success", type = "freemarker", location = "/WEB-INF/theme/default/shop/goodsdetail.ftl") })
	public String getGoodsDetail() {
		this.dataCollectionTAction.putBaseInfoToContext();
		if (StringUtils.isNotBlank(this.getGoodsid())) {
			GoodsT g = this.goodsTService.findByPK(GoodsT.class,
					this.getGoodsid());
			if (g != null) {
				ActionContext.getContext().put(FreeMarkervariable.GOODSDETAIL,
						g);
				GoodsDetailRpT gd = dataCollectionTAction
						.getGoodsDetailRpByGoodsId(this.getGoodsid());
				if (gd != null) {
					ActionContext.getContext().put(FreeMarkervariable.GOODSDES,
							gd);
				}
				//计算评论数据
				getCommentThencalCommentStar();
			}
		}
		return SUCCESS;
	}

	private void getCommentThencalCommentStar(){
		RedisGoodsCommentVo rCommentVo=(RedisGoodsCommentVo) redisBaseTService.get(FreeMarkervariable.GOODSCOMMENTS+this.getGoodsid()+this.getPage(), RedisGoodsCommentVo.class);
		if(rCommentVo==null){
			rCommentVo=new RedisGoodsCommentVo();
			//获取分类评论数据
			int currentPage=page;
			int lineSize=rp;
			Map<String,String>params=new HashMap<>();
			params.put("goodsid", this.getGoodsid());
			Criterion criterion=Restrictions.allEq(params);
			Order order=Order.desc("posttime");
			List<GoodsCommentT>gCommentTs=this.goodsCommentTService.findByCriteriaByPage(GoodsCommentT.class, criterion, order, currentPage, lineSize);
			rCommentVo.setGoodsCommentTs(gCommentTs);
			int total=this.goodsCommentTService.count(GoodsCommentT.class, criterion).intValue();
			rCommentVo.setTotal(total);
			//计算评论星级1
			Map<String, Object>params1=new HashMap<String, Object>();
			params1.put("goodsid", this.getGoodsid());
			params1.put("score",1);
			Criterion criterion2=Restrictions.allEq(params1);
			int star1=this.goodsCommentTService.count(GoodsCommentT.class, criterion2).intValue();
			if(total!=0&&star1!=0){
				Double ds1=Arith.div(Double.parseDouble(String.valueOf(star1)),Double.parseDouble(String.valueOf(rCommentVo.getTotal())));
				rCommentVo.setOneStar(ds1.intValue()*100);
			}
			//计算评论星级2
			Map<String, Object>params2=new HashMap<String, Object>();
			params2.put("goodsid", this.getGoodsid());
			params2.put("score",2);
			Criterion criterion3=Restrictions.allEq(params2);
			int star2=this.goodsCommentTService.count(GoodsCommentT.class, criterion3).intValue();
			if(total!=0&&star2!=0){
				Double ds2=Arith.div(Double.parseDouble(String.valueOf(star2)),Double.parseDouble(String.valueOf(rCommentVo.getTotal())));
				rCommentVo.setTwoStar(ds2.intValue()*100);
			}
			//计算评论星级3
			Map<String, Object>params3=new HashMap<String, Object>();
			params3.put("goodsid", this.getGoodsid());
			params3.put("score",3);
			Criterion criterion4=Restrictions.allEq(params3);
			int star3=this.goodsCommentTService.count(GoodsCommentT.class, criterion4).intValue();
			if(total!=0&&star3!=0){
				Double ds3=Arith.div(Double.parseDouble(String.valueOf(star3)),Double.parseDouble(String.valueOf(rCommentVo.getTotal())));
				rCommentVo.setThreeStar(ds3.intValue()*100);
			}
			//计算评论星级4
			Map<String, Object>params4=new HashMap<String, Object>();
			params4.put("goodsid", this.getGoodsid());
			params4.put("score",4);
			Criterion criterion5=Restrictions.allEq(params4);
			int star4=this.goodsCommentTService.count(GoodsCommentT.class, criterion5).intValue();
			if(total!=0&&star4!=0){
				Double ds4=Arith.div(Double.parseDouble(String.valueOf(star4)),Double.parseDouble(String.valueOf(rCommentVo.getTotal())));
				rCommentVo.setFourStar(ds4.intValue()*100);
			}
			//计算评论星级5
			Map<String, Object>params5=new HashMap<String, Object>();
			params5.put("goodsid", this.getGoodsid());
			params5.put("score",5);
			Criterion criterion6=Restrictions.allEq(params5);
			int star5=this.goodsCommentTService.count(GoodsCommentT.class, criterion6).intValue();
			if(total!=0&&star5!=0){
				Double ds5=Arith.div(Double.parseDouble(String.valueOf(star5)),Double.parseDouble(String.valueOf(rCommentVo.getTotal())));
				rCommentVo.setFiveStar(ds5.intValue()*100);
			}
			redisBaseTService.put(FreeMarkervariable.GOODSCOMMENTS+this.getGoodsid()+this.getPage(), rCommentVo, RedisGoodsCommentVo.class,10,TimeUnit.MINUTES);
		}
		PageModel<GoodsCommentT>pm=new PageModel<GoodsCommentT>(page,rp,rCommentVo.getGoodsCommentTs(),rCommentVo.getTotal());
		String action=BaseTools.getBasePath()+"/goods/getGoodsDetail.action?goodsid="+this.getGoodsid();
		ActionContext.getContext().put(FreeMarkervariable.ACTIONLINK, action);
		ActionContext.getContext().put(FreeMarkervariable.GOODSCOMMENTS, pm);
		ActionContext.getContext().put(FreeMarkervariable.COMMENTSTARONE, rCommentVo.getOneStar());
		ActionContext.getContext().put(FreeMarkervariable.COMMENTSTARTWO, rCommentVo.getTwoStar());
		ActionContext.getContext().put(FreeMarkervariable.COMMENTSTARTHREE, rCommentVo.getThreeStar());
		ActionContext.getContext().put(FreeMarkervariable.COMMENTSTARFOUR, rCommentVo.getFourStar());
		ActionContext.getContext().put(FreeMarkervariable.COMMENTSTARFIVE, rCommentVo.getFiveStar());
	}
	
	/**
	 * 保存商品评论
	 * @return
	 */
	@Action(value = "saveGoodsComment", results = { @Result(name = "json", type = "json") })
	public String saveGoodsComment(){
		MemberT memberT=(MemberT) ActionContext.getContext().getSession().get(StaticKey.MEMBER_SESSION_KEY);
		if(memberT!=null){
			if(StringUtils.isNotBlank(this.getCommentcontent())&&StringUtils.isNotBlank(this.getGoodsid())){
				GoodsT g=this.goodsTService.findByPK(GoodsT.class, this.getGoodsid());
				if(g!=null){
					GoodsCommentT gct=new GoodsCommentT();
					gct.setCommentid(this.getSerial().Serialid(Serial.GOODSCOMMENT));
					gct.setCommentcontent(StringUtils.trim(this.getCommentcontent()));
					gct.setEmailable(StaticKey.ZERO);//不进行邮件通知
					gct.setGoodsid(this.getGoodsid());
					gct.setGoodsname(g.getGoodsname());
					gct.setPosttime(BaseTools.getSystemTime());
					gct.setReplyid(StaticKey.EMPTY);
					gct.setReplyorcomment(StaticKey.EMPTY);
					gct.setReplyorcommentuserid(memberT.getId());
					gct.setReplyorcommentusername(memberT.getLoginname());
					gct.setScore(this.getScore());
					gct.setShopid(StaticKey.ZERO);
					gct.setState(DataShowState.SHOW.getState());
					gct.setTitle(this.getGoodsname());
					gct.setVirtualadd(StaticKey.COMMENT_VIRTUALADD_ONE_NUM);
					this.goodsCommentTService.save(gct);
					
					g.setTotalcomment(g.getTotalcomment()+1);
					g.setTotalstar(g.getTotalstar()+gct.getScore());
					g.setTotalstaruser(g.getTotalstaruser()+1);
					this.goodsTService.update(g);
				}
				this.setSucflag(true);
				return JSON;
			}else{
				this.setMsg("参数错误");
			}
		}
		this.setMsg("登陆失效");
		return JSON;
	}
	
	
	private boolean sucflag;
	private String msg;
	/**
	 * 商品评论内容
	 */
	private String commentcontent;
	/**
	 * 商品名称
	 */
	private String goodsname;
	/**
	 * 星级
	 */
	private int score;
	
	private String goodsid;

	private int rp=10;
	
	private int page=1;
	
	public int getRp() {
		return rp;
	}

	public void setRp(int rp) {
		this.rp = rp;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public String getGoodsid() {
		return goodsid;
	}

	public void setGoodsid(String goodsid) {
		this.goodsid = goodsid;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getCommentcontent() {
		return commentcontent;
	}

	public void setCommentcontent(String commentcontent) {
		this.commentcontent = commentcontent;
	}

	public String getGoodsname() {
		return goodsname;
	}

	public void setGoodsname(String goodsname) {
		this.goodsname = goodsname;
	}

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		this.score = score;
	}

	public boolean isSucflag() {
		return sucflag;
	}

	public void setSucflag(boolean sucflag) {
		this.sucflag = sucflag;
	}

}
